<?php
// 检查食材关联数据的脚本

// 数据库配置
$config = [
    'hostname' => '127.0.0.1',
    'database' => 'yingyang',
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8mb4'
];

try {
    // 数据库连接
    $dsn = "mysql:host={$config['hostname']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== 数据库连接成功 ===\n\n";
    
    // 查询最近处理的10个菜品
    echo "=== 最近处理的10个菜品 ===\n";
    $stmt = $pdo->query('SELECT id, name, cook_time, updatetime FROM fa_food_dish WHERE ai_called = 1 ORDER BY updatetime DESC LIMIT 10');
    $dishes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($dishes as $dish) {
        echo "菜品ID: " . $dish['id'] . ", 名称: " . $dish['name'] . ", 烹饪时长: " . $dish['cook_time'] . ", 更新时间: " . $dish['updatetime'] . "\n";
        
        // 查询该菜品的食材关联数据
        $relStmt = $pdo->prepare('SELECT * FROM fa_food_ingredientrel WHERE dish_id = ?');
        $relStmt->execute([$dish['id']]);
        $ingredients = $relStmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($ingredients)) {
            echo "  该菜品没有食材关联数据\n";
        } else {
            echo "  食材关联数量: " . count($ingredients) . "\n";
            foreach ($ingredients as $ingredient) {
                echo "    食材: " . $ingredient['ingredient_name'] . ", 用量: " . $ingredient['quantity'] . ", 食材ID: " . $ingredient['ingredient_id'] . "\n";
            }
        }
        echo "\n";
    }
    
    // 统计总的数量
    $totalDishStmt = $pdo->query('SELECT COUNT(*) as total FROM fa_food_dish WHERE ai_called = 1');
    $totalDish = $totalDishStmt->fetch(PDO::FETCH_ASSOC);
    
    $totalRelStmt = $pdo->query('SELECT COUNT(*) as total FROM fa_food_ingredientrel');
    $totalRel = $totalRelStmt->fetch(PDO::FETCH_ASSOC);
    
    echo "=== 统计信息 ===\n";
    echo "已处理菜品总数: " . $totalDish['total'] . "\n";
    echo "食材关联记录总数: " . $totalRel['total'] . "\n";
    
} catch (Exception $e) {
    echo "查询失败: " . $e->getMessage() . "\n";
}
?>